<?php

declare(strict_types=1);

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Server\ServerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\Redis\Redis;

if (!function_exists('di')) {
    /**
     * Finds an entry of the container by its identifier and returns it.
     * @param null|mixed $id
     * @return mixed|ContainerInterface
     */
    function di($id = null): ContainerInterface
    {
        $container = ApplicationContext::getContainer();
        if ($id) {
            return $container->get($id);
        }
        return $container;
    }
}

/**
 * redis 客户端实例
 */
if (!function_exists('redis')) {
    function redis(): Redis
    {
        return di()->get(Redis::class);
    }
}

/**
 * server 实例 基于 swoole server
 */
if (!function_exists('server')) {
    function server()
    {
        return di()->get(ServerFactory::class)->getServer()->getServer();
    }
}

/**
 * websocket 实例
 */
if (!function_exists('websocket')) {
    function websocket()
    {
        return di()->get(\Hyperf\WebSocketServer\Server::class)->getServer();
    }
}

/**
 * 缓存实例 简单的缓存
 */
if (!function_exists('cache')) {
    function cache(): \Psr\SimpleCache\CacheInterface
    {
        return di()->get(Psr\SimpleCache\CacheInterface::class);
    }
}

/**
 * 控制台日志
 */
if (!function_exists('stdLog')) {
    function stdLog(): StdoutLoggerInterface
    {
        return di()->get(StdoutLoggerInterface::class);
    }
}

/**
 * 文件日志
 */
if (!function_exists('logger')) {
    function logger(): \Psr\Log\LoggerInterface
    {
        return di()->get(LoggerFactory::class)->make();
    }
}

/**
 *
 */
if (!function_exists('request')) {
    function request(): ServerRequestInterface
    {
        return di()->get(ServerRequestInterface::class);
    }
}

/**
 *
 */
if (!function_exists('response')) {
    function response(): ResponseInterface
    {
        return di()->get(ResponseInterface::class);
    }
}

if (!function_exists('success')) {
    /**
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return array
     */
    function success(array $data = [], string $msg = 'success', int $code = 200): array
    {
        return ['code' => $code, 'data' => $data, 'msg' => $msg];
    }
}

if (!function_exists('error')) {
    /**
     * @param string $msg
     * @param array $data
     * @param int $code
     * @return array
     */
    function error(string $msg = 'error', array $data = [], int $code = 500): array
    {
        return ['code' => $code, 'data' => $data, 'msg' => $msg];
    }
}